package com.mybatis.lo.builder;

import com.mybatis.lo.config.Configuration;
import com.mybatis.lo.factory.DefaultSqlSessionFactory;
import com.mybatis.lo.factory.SqlSessionFactory;
import com.mybatis.lo.utils.DocumentUtils;
import org.dom4j.Document;

import java.io.InputStream;
import java.io.Reader;

/**
 * 配置解析入口，`SqlSessionFactory`构建器，可以通过不同材料构建工厂类
 * @author zhangbh
 * 2023-06-16 07:30
 **/
public class SqlSessionFactoryBuilder {

    public static SqlSessionFactory build(InputStream inputStream) {
        Document document = DocumentUtils.createDocument(inputStream);
        Configuration configuration = new Configuration();
        XMLConfigurationBuilder builder = new XMLConfigurationBuilder(configuration);
        builder.loadConfiguration(document.getRootElement());
        return build(configuration);
    }

    public static SqlSessionFactory build(Reader reader) {
        Document document = DocumentUtils.createDocument(reader);
        Configuration configuration = new Configuration();
        XMLConfigurationBuilder builder = new XMLConfigurationBuilder(configuration);
        builder.loadConfiguration(document.getRootElement());
        return build(configuration);
    }

    /**
     * 获取到构建的工厂
     * @return SqlSessionFactory类
     */
    private static SqlSessionFactory build(Configuration configuration) {
        return new DefaultSqlSessionFactory(configuration);
    }
}
